var roleStatusMap = {       
    'DEAD'   : 0,  //死亡
    'NORMAL' : 1,  //正常
    'CONFUSE': 2,  //魅惑
    'SLEEP'  : 3,  //睡眠
};

var soldierKindMap = {
    'SWORD'   : 1,  //刀
    'SPEAR'   : 2,  //枪
    'RIDER'   : 3,  //骑
    'ADVISER' : 4,  //谋士
    'BEAUTY'  : 5,  //红颜
};

var defRespMap = {      
    'MISS' : 2,   //闪避
    'CRIT' : 3,   //暴击
    'BLOCK': 4,   //格挡
};

var batModMap = {   
    'DUPLICATE' : 0,   //副本                 
    'TOWER'     : 1,   //勇闯重楼         
    'KILL'      : 2,   //过关斩将       
    'PVP'       : 3,   //
    'TOMB'      : 4,   //古墓宝藏
    'DIGTREASURE' : 5, // 地下宝藏
    'MYBATTLE'  : 6,   // 个人战役
};

exports.save_team = function(player, req, resp, onHandled){
    do{
        if(!req.args.team || typeof(req.args.team) != 'object'){
            resp.code = 1; resp.desc = 'no valid args:team'; break;
        }
        
        var user = player.user;
        var role = user.role;
        var team = req.args.team;
        var ridMap = {};
        
        var isRidOk = true;
        for( var pos=0; pos<9; pos++ ) {
            var rid = team[pos];  
            if( isNaN(rid) ) {
                isRidOk = false;
                break;
            }

            rid = Math.round(rid);
            if( 0 == rid ) {
                continue; 
            }

            if( !gConfRole[rid] ) {
                isRidOk = false;
                break;
            }

            if( rid in ridMap ) {
                isRidOk = false;
                break;
            }

            if( !(rid in role) ) {
                isRidOk = false;
                break;
            }

            ridMap[rid] = 1;
        }

        if( !isRidOk ) {
            resp.code = 1; resp.desc = 'not valid'; break; 
        }
        
        var roleNumber = Object.keys(ridMap).length;
        if( roleNumber > +gConfLevel[user.status.level].RoleNum  || roleNumber < 1) {
            resp.code = 1; resp.desc = 'role number error'; break;
        }

        player.roleDirty = true;
        player.battleWorldSaveTeam = true; 
        user.team = team;
        player.markDirty('team');
        player.getFightForce();
        player.doTask('ArrangeTeam', 'all');
        
    }while(false);       

    onHandled();
}

exports.reset_tower = function(player, req, resp, onHandled){
    do {
        if( isNaN(req.args.cash) || isNaN(req.args.tower) ){
            resp.code = 1; resp.desc = 'no valid args'; break;
        }

        var isCash = (+req.args.cash > 0) ? true : false;
        var towerId = parseInt(req.args.tower);
        
        var user = player.user;
        var tower = user.tower;
        var costCash = 0;
        
        if( !tower.highest[towerId] ) {
            resp.code = 1; resp.desc = 'no reach tower'; break;
        }

        if( !isCash && tower.free >= +gConfGlobal.ParidisDailyLimit ) {
            resp.code = 1; resp.desc = 'no more free'; break;
        }

        if( !isCash ) {
            tower.free += 1;
        }else {
            var maxCashReset = 0;
            if( user.status.vip ) {
                maxCashReset += gConfVip[user.status.vip].TowerResetAdd;
            }
            if( tower.cash >= maxCashReset ) {
                resp.code = 1; resp.desc = 'no more to buy'; break;
            }

            var confBuy = gConfBuy[tower.cash + 1]; 
            if( !confBuy ) {
                resp.code = 1; resp.desc = 'no more to buy'; break;
            }
            
            costCash = +confBuy.CashTower;
            if( !costCash ) {
                resp.code = 1; resp.desc = 'no more to buy'; break;
            }

            if( !player.costResource('cash', costCash, tower.cash) ){
                resp.code = 1; resp.desc = 'not enough cash'; break;
            }

            tower.cash += 1;
        }
        
        tower.current[towerId] = 0;
        player.markDirty('tower');

        resp.data.tower = tower;
        resp.data.cash = -costCash; 
    
    }while(false);       
    
    onHandled();
}

exports.duplicate = function(player, req, resp, onHandled){
    do {
        if( isNaN(req.args.id) ){
            resp.code = 1; resp.desc = 'no valid args'; break;
        }

        var aktId = req.uid;
        var battleId = +req.args.id;
        var battleConf = gConfBattle[battleId];
        if( !battleConf ) {
            resp.code = 1; resp.desc = 'no valid args'; break;
        }

        var user = player.user;
        
        // 精英副本
        if( battleId > 10000 ) {
            if( ((battleConf.Battle - 1) * 20 > user.duplicate) 
                && battleConf.Battle  > gConfBattle[user.duplicate].Battle ) {
                resp.code = 1; resp.desc = 'not reach'; break;
            }
        }else if( battleId > (user.duplicate+1) ) {
            resp.code = 1; resp.desc = 'not reach'; break;
        }

        if( user.status.level < battleConf.LevelLimit ) {
            resp.code = 1; resp.desc = 'level limit'; break;
        }

        var attacker = new Fighter();
        var defender = new Fighter();

        attacker.initWithPlayer(player);
        defender.initWithMonster(batModMap.DUPLICATE, battleId, battleConf);

        var costFood = gConfGlobal.DuplicateFood;
        if( battleId > 10000 ) {
            costFood = gConfGlobal.DuplicateBossFood;
        }

        if( user.status.food < costFood ){
            resp.code = 1;
            resp.desc = 'food not enough';
            break; 
        }
        
        var addXp = 0;
        var addHonor = 0;
        var addGold = 0;

        var battleReport = attacker.fight(defender);
        if( battleReport.success ) {
            var roles = {};
            var team = user.team;

            addXp = +battleConf.Xp;
            addHonor = +battleConf.Honor;
            addGold = +battleConf.Gold;
            player.addXp(addXp);

            user.status.gold += addGold;
            user.status.honor += addHonor;
            user.status.food += -costFood;

            player.markDirty('status');
            
            for( var pos in team){
                var rid = team[pos];
                if( !rid ){
                    continue;
                }

                var role = user.role[rid];
                if( role.level >= user.status.level ) {
                    continue; 
                }

                //更新英雄的经验和等级,重新计算战斗力
                if( player.addRoleXp(role, battleConf.HeroXp) ) {
                    player.roleDirty = true;
                }
                roles[rid] = {'level':role.level, 'xp':role.xp};
            }

            //获取精英奖励
            if( battleId > 10000 ) {
                var material = {};
                var materialId = battleConf.Material;
                var materialNum = battleConf.MaterialNum;
                player.addInventory('material', materialId, materialNum);

                material[materialId] = materialNum;
                resp.data.material = material;
            }else if( battleId > user.duplicate ) {
                user.duplicate = battleId;
                player.markDirty('duplicate');
            }

            player.doTask('WinPVE', battleId);
            player.checkEvent('Duplicate', battleId);
        }else {
            costFood = 0;
        }

        player.doDailyTask(gConfDailyTask.PVE);
        player.doTask('FightPVE', 'all');
        player.doTask('FightPVETo', battleId);

        resp.data.battle = battleReport;
        resp.data.xp = addXp;
        resp.data.level = user.status.level;
        resp.data.honor = addHonor;
        resp.data.food = -costFood;
        resp.data.gold = addGold;
        resp.data.roles = roles;
        resp.daily_task = gConfDailyTask.PVE;
                                
    }while(false);   
    
    onHandled();
}

exports.tower = function(player, req, resp, onHandled){
    do{
        if( isNaN(req.args.id) || isNaN(req.args.tower) ){
            resp.code = 1; resp.desc = 'no valid args'; break;
        }

        var aktId = req.uid;
        var towerId = parseInt(req.args.tower);
        var defId = parseInt(req.args.id);
        
        var user = player.user;
        var tower = user.tower;
        if( !(towerId in gConfTower) || !(defId in gConfTower[towerId]) ) {
            resp.code = 1; resp.desc = 'invalid args'; break;
        }
        
        if( !(towerId in tower.current) && (tower.highest[towerId - 1] < 100) ) {
            resp.code = 1; resp.desc = 'not reach floor'; break;
        }

        if( !(towerId in tower.current) ) {
            tower.current[towerId] = 0; 
            tower.highest[towerId] = 0;
        }

        if( defId != (tower.highest[towerId] + 1) ) {
            resp.code = 1; resp.desc = 'no valid args'; break;
        }

        var attacker = new Fighter();
        var defender = new Fighter();

        var towerConf = gConfTower[towerId][defId];
        attacker.initWithPlayer(player);
        defender.initWithMonster(batModMap.TOWER, defId, towerConf);

        var isOnTeam = 0;
        for( var pos in attacker.team ){
           if(attacker.team[pos])
           {
              isOnTeam = 1;
              break;
           }
        }

        if( !isOnTeam ){
            resp.code = 1;
            resp.desc = "no hero on team";
            break;
        }

        var battleReport = attacker.fight(defender);
        var success = battleReport.success;

        if( success ) {
            if( defId > tower.current[towerId] ){
                tower.current[towerId] = defId;
                //历史最高层 
                if( defId > tower.highest[towerId] ){
                    tower.highest[towerId] = defId; 
                    var worldReq = {
                        uid: req.uid,
                        mod: 'rank',
                        act: 'update_tower',
                        args: {
                            tower : towerId,
                            name: user.info.un,
                            headpic: user.info.headpic,
                            floor: defId,
                            fight_force: player.getFightForce()
                        }
                    };
                    var worldResp = {};
                    requestWorld(worldReq, worldResp);
                     
                    if( 1 == towerId ) {
                        var worldReq1 = {
                            uid: req.uid,
                            mod: 'rank',
                            act: 'update_tower_activity_rank',
                            args: {
                                name: user.info.un,
                                headpic: user.info.headpic,
                                floor: defId,
                            }
                        };
                        var worldResp1 = {};
                        requestWorld(worldReq1, worldResp1);
                    }

                    player.checkEvent('TowerLevel', towerId);
                }
            }
        }

        player.markDirty('tower');
        
        var addHonor = 0;
        var awards = [];

        if( success ){
            addHonor = +towerConf.Honor;

            user.status.honor += addHonor;
            player.markDirty('status.honor');

            //获取material 奖励
            var award = towerConf.Award1;
            if( award ) {
                awards.push(award);
                awards = player.addAwards(awards); 
            } 

            player.doTask('FightTowerTo',defId);
            if( !gConfTower[towerId][defId+1] ) {
                gMessage.addSystemMessage('tower_pass', [user.info.un, towerConf.Name]);
            }
        } 

        player.doDailyTask(gConfDailyTask.ChallengeTower);
        player.doTask('FightTower','all');
        
        resp.data.battle = battleReport;
        resp.data.honor = addHonor;
        resp.data.awards = awards;
        resp.data.tower = user.tower;

        resp.daily_task = gConfDailyTask.ChallengeTower;
                                
    }while(false);   

    onHandled();
}

exports.kill = function(player, req, resp, onHandled){
    do{
        if( isNaN(req.args.id) || req.args.roles.constructor != Array
            || req.args.roles.length != 3 || isNaN(req.args.pos) ) {
            resp.code = 1; resp.desc = 'no valid args'; break;
        }

        var defId = +req.args.id;
        var pos = Math.floor(+req.args.pos);
        var atkRoleArr = req.args.roles;

        var user = player.user;

        var atkFightForce = [0,0,0];
        var defFightForce = [0,0,0];

        var killConf = gConfKillGeneral[defId];
        if( !killConf ) {
            resp.code = 1; resp.desc = "id error"; break;
        }
        
        var kill = user.kill;
        if( kill.progress != defId || (kill.position+1) != pos ) {
            resp.code = 1; resp.desc = "not reach"; break;
        }

        player.calculateTeamRoleAttr();
        
        var isRidOk = true;
        for( var i = 0, len = atkRoleArr.length; i < len; i++ ){
            var rid = atkRoleArr[i];

            if( !rid ){
                isRidOk = false;
                break;
            }

            var role = user.role[rid];

            if( !role ) {
                isRidOk = false;
                break;
            } 
            
            atkFightForce[i] = role.fight_force;
        }

        if( !isRidOk ){
            resp.code = 1; resp.desc = "invalid roles"; break;
        }

        for( var i = 0; i < 3; i++ ){
            defFightForce[i] = killConf[util.format('FightForce%d_%d', pos, i+1)];
        }
        
        var result = [0, 0, 0];
        for( var i = 0; i < atkFightForce.length; i++ ){
            var diffFightForce = atkFightForce[i] - defFightForce[i]; 

            var win = 0;
            if( 0 == diffFightForce ){
                win = common.randRange(0, 1);
            }else{
                win = diffFightForce > 0 ? 1 : 0;
            }

            result[i] = win;
        }

        var addHonor = 0;
        var material = {};
        if( result.sum() > 1 && pos == 3 ){
            // 通关
            addHonor = killConf.Honor;

            var materialId = killConf.Material;
            var materialNum = killConf.MaterialNum;
            material[materialId] = materialNum;

            player.addInventory('material', materialId, materialNum);

            user.status.honor += addHonor;
            player.markDirty('status.honor'); 
            player.doTask('KillGeneralTo', defId);

            kill.progress = defId+1;
            kill.position = 0;

            if( !gConfKillGeneral[kill.progress] ) {
                gMessage.addSystemMessage('kill_general', [user.info.un]);
            }

            if (!kill.maxProgress || defId > kill.maxProgress) {
                kill.maxProgress = defId;
                player.markDirty('kill.maxProgress');
                player.checkEvent('KillGeneralLevel');
            }

        }else if( result.sum() > 1 ) {
            kill.position = pos;
        }

        player.markDirty('kill.progress');
        player.markDirty('kill.position');

        player.doDailyTask(gConfDailyTask.KillGeneral);
        player.doTask('KillGeneral','all');
        
        resp.data.result = result;
        resp.data.honor = addHonor;
        resp.data.material = material;
        resp.daily_task = gConfDailyTask.KillGeneral;
                                
    }while(false);   

    onHandled();
}

exports.reset_kill = function(player, req, resp, onHandled){
    do {
        if( isNaN(req.args.id) || isNaN(req.args.cash) ){
            resp.code = 1; resp.desc = 'no valid args'; break;
        }
        
        var battleId = +req.args.id;
        var isCash = (+req.args.cash > 0) ? true : false;
        
        var user = player.user;
        var kill = user.kill;
        var costCash = 0;

        if( !gConfKillGeneral[battleId] || !gConfKillGeneral[battleId].Material ) {
            resp.code = 1; resp.desc = 'invalid battle id'; break;
        }
        
        if( kill.progress <= battleId ) {
            resp.code = 1; resp.desc = 'not reach'; break;
        }

        if( !isCash && kill.free >= gConfGlobal.KillRoleDailyLimit ) {
            resp.code = 1; resp.desc = 'no more free'; break;
        }

        if( !isCash ){
            kill.free += 1;
            player.markDirty('kill.free');
        }else {
            var maxCashReset = 0;
            if( user.status.vip ) {
                maxCashReset += gConfVip[user.status.vip].KillResetAdd;
            }
            if( kill.cash >= maxCashReset ) {
                resp.code = 1; resp.desc = 'no more to buy'; break;
            }

            var confBuy = gConfBuy[kill.cash + 1]; 
            if( !confBuy ) {
                resp.code = 1; resp.desc = 'no more to buy'; break;
            }
            
            costCash = confBuy.CashKill;
            if( !costCash ) {
                resp.code = 1; resp.desc = 'no more to buy'; break;
            }

            if( !player.costResource('cash', costCash, kill.cash) ){
                resp.code = 1; resp.desc = 'not enough cash'; break;
            }

            kill.cash += 1;
            player.markDirty('kill.cash');
        }

        kill.reset[battleId] = 1;
        player.markDirty(util.format('kill.reset.%d', battleId));

        resp.data.cash = -costCash;
    
    }while(false);
    
    onHandled();
}

exports.auto_kill = function(player, req, resp, onHandled){
    do {
        if( isNaN(req.args.id) ) {
            resp.code = 1; resp.desc = 'no valid args'; break;
        }
        
        var battleId = +req.args.id;
        
        var user = player.user;
        var kill = user.kill;

        var killConf = gConfKillGeneral[battleId];
        if( !killConf ) {
            resp.code = 1; resp.desc = 'invalid battle id'; break;
        }
        
        if( !kill.reset[battleId] ) {
            resp.code = 1; resp.desc = 'not reset'; break;
        }

        var addHonor = killConf.Honor;
        var material = {};

        var materialId = killConf.Material;
        var materialNum = killConf.MaterialNum;
        material[materialId] = materialNum;

        player.addInventory('material', materialId, materialNum);

        user.status.honor += addHonor;
        player.markDirty('status.honor'); 
        player.doTask('KillGeneral', 'all');

        kill.reset[battleId] = 0;
        
        player.markDirty(util.format('kill.reset.%d', battleId));
        player.doDailyTask(gConfDailyTask.KillGeneral);

        resp.data.honor = addHonor;
        resp.data.material = material;
        resp.daily_task = gConfDailyTask.KillGeneral;
    
    }while(false);
    
    onHandled();
}

exports.auto_duplicate = function(player, req, resp, onHandled){
    do {
        if( isNaN(req.args.id) || isNaN(req.args.round) ){
            resp.code = 1; resp.desc = 'no valid args'; break;
        }
        
        var aktId = req.uid;
        var battleId = +req.args.id;
        var round = Math.round(req.args.round);

        if( round < 1 ) {
            resp.code = 1; resp.desc = 'invalid round'; break;
        }

        var user = player.user;
        if( user.status.level < 29 ) {
            resp.code = 1; resp.desc = 'level less than 29'; break;
        }

        if( battleId > 10000 ) {
            resp.code = 1; resp.desc = 'boss battle'; break;
        }

        var battleConf = gConfBattle[battleId];
        if( !battleConf ) {
            resp.code = 1; resp.desc = 'no valid args'; break;
        }

        if( battleId > user.duplicate ) {
            resp.code = 1; resp.desc = 'not reach'; break;
        }

        var costFood = round * gConfGlobal.DuplicateFood;
        if(user.status.food < costFood){
            resp.code = 1; resp.desc = 'food not enough'; break; 
        }

        var roles = {};
        var team = user.team;
        var addXp = round * battleConf.Xp;
        var addHonor = round * battleConf.Honor;
        var addGold = round * battleConf.Gold;

        player.addXp(addXp);

        user.status.gold += addGold;
        user.status.honor += addHonor;
        user.status.food += -costFood;
        player.markDirty('status');

        var roleXp = round * battleConf.HeroXp;
        for( var pos in team){
            var rid = team[pos];
            if( !rid ){
                continue;
            }

            var role = user.role[rid];
            if( role.level >= user.status.level ) {
                continue;  
            }

            //更新英雄的经验和等级,重新计算战斗力
            if( player.addRoleXp(role, roleXp) ) {
                player.roleDirty = true;
            }
            roles[rid] = {'level':role.level, 'xp':role.xp};
        }

        player.doTask('RadePVE', battleId);

        resp.data.xp = addXp;
        resp.data.level = user.status.level;
        resp.data.honor = addHonor;
        resp.data.food = -costFood;
        resp.data.gold = addGold;
        resp.data.roles = roles;
    }while(false);   
    
    onHandled();
}

exports.auto_tower = function(player, req, resp, onHandled){
    do{
        if( isNaN(req.args.tower) ){
            resp.code = 1; resp.desc = 'no valid args'; break;
        }

        var towerId = parseInt(req.args.tower);

        var user = player.user;
        var tower = user.tower;
        var highest = tower.highest;

        if( !tower.highest[towerId] ) {
            resp.code = 1; resp.desc = 'no reach tower'; break;
        }

        if( tower.current[towerId] > 0 ) {
            resp.code = 1; resp.desc = 'not reset'; break;
        }

        var awards = [];
        var awardTower = {};
        var addHonor = 0;
        for( var floor = 1; floor <= highest[towerId]; floor++){
            var towerConf = gConfTower[towerId][floor];
            addHonor += +towerConf.Honor;

            //获取material 奖励
            var award = towerConf.Award1;
            if( award ) {
                var type = award[0];
                var id = award[1];
                var num = award[2];
                if( 'material' == type) {
                    if( !('material' in awardTower) ) {
                        awardTower.material = {};
                    }

                    if( !(id in awardTower.material) ) {
                        awardTower.material[id] = num; 
                    }else {
                        awardTower.material[id] += num; 
                    }
                }
                
            }    
            
            player.doTask('FightTowerTo',floor);
            player.doTask('FightTower','all');
        }

        for( var type in awardTower ) {
            if( 'material' == type ) {
                var material = awardTower.material; 
                for( var id in material ) {
                    awards.push(['material',id, +material[id]]);
                }
            }
        }

        awards = player.addAwards(awards); 

        user.status.honor += addHonor;
        player.markDirty('status.honor');

        tower.current[towerId] = highest[towerId];
        player.markDirty('tower');

        player.doDailyTask(gConfDailyTask.ChallengeTower);

        resp.daily_task = gConfDailyTask.ChallengeTower;
        resp.data.honor = addHonor;
        resp.data.awards = awards;
        resp.data.tower = user.tower;

        var worldReq = {
            uid: req.uid,
            mod: 'rank',
            act: 'update_tower',
            args: {
                tower : towerId,
                name: user.info.un,
                headpic: user.info.headpic,
                floor: highest[towerId],
                fight_force: player.getFightForce()
            }
        };
        var worldResp = {};
        requestWorld(worldReq, worldResp);
                                
    }while(false);   

    onHandled();
}

exports.buy_food = function(player, req, resp, onHandled){
    do {
        var user = player.user;

        var canBuy = gConfGlobal.BuyFoodLimit;
        if( user.status.vip ) {
            canBuy += gConfVip[user.status.vip].BuyFood;
        }

        if( user.mark.food >= canBuy ) {
            resp.code = 1; resp.desc = 'no more to buy'; break;
        }

        var confBuy = gConfBuy[user.mark.food + 1]; 
        if( !confBuy ) {
            resp.code = 1; resp.desc = 'no more to buy'; break;
        }
        
        var costCash = confBuy.CashFood;
        if( !costCash ) {
            resp.code = 1; resp.desc = 'no more to buy'; break;
        }

        if( !player.costResource('cash', costCash, user.mark.food) ) {
            resp.code = 1; resp.desc = 'not enough cash';break;
        }

        var addFood = gConfGlobal.CashFood;
        user.status.food += addFood;
        user.mark.food += 1;
        
        player.markDirty('status.food');
        player.markDirty('mark.food');

        resp.data.food = addFood ;
        resp.data.cash = -costCash;
    }while(false);
    
    onHandled();
}

exports.mybattle = function(player, req, resp, onHandled){
    do {
        if( isNaN(req.args.id) ){
            resp.code = 1; resp.desc = 'no valid args'; break;
        }

        var aktId = req.uid;
        var battleId = parseInt(req.args.id);
        var battleConf = gConfMyBattle[battleId];
        if( !battleConf ) {
            resp.code = 1; resp.desc = 'no id'; break;
        }

        var user = player.user;
        if( user.status.level < battleConf.LevelLimit ) {
            resp.code = 1; resp.desc = 'level limit'; break;
        }

        if( gConfBattle[user.duplicate + 1] ) {
            resp.code = 1; resp.desc = 'duplicate limit'; break;
        }

        var myBattle = user.mybattle;
        var myBattleProgress = myBattle.progress;
        if( 0 == myBattle.max ) {
            // 开启个人战役
            myBattleProgress[gConfMyBattle[myBattle.max + 1].Battle] = 0;
        }
        
        // 战役ID
        var battleFieldId = battleConf.Battle;
        if( !(battleFieldId in myBattleProgress) ) {
            if( battleId != myBattle.max + 1 ) {
                resp.code = 1; resp.desc = 'id error'; break;
            }else {
                myBattleProgress[battleFieldId] = 0; 
            }
        }

        // 战役中最小的关卡ID
        var battleFieldMin = (battleFieldId - 1) * 5 + 1; 
        if( !myBattleProgress[battleFieldId] && (battleId != battleFieldMin) ) {
            resp.code = 1; resp.desc = 'id error'; break;
        }else if ( myBattleProgress[battleFieldId] && (battleId != myBattleProgress[battleFieldId] + 1) ) {
            resp.code = 1; resp.desc = 'id error'; break;
        }

        var attacker = new Fighter();
        var defender = new Fighter();

        attacker.initWithPlayer(player);
        defender.initWithMonster(batModMap.MYBATTLE, battleId, battleConf);

        var costFood = battleConf.FoodCost;
        if( user.status.food < costFood ){
            resp.code = 1;
            resp.desc = 'food not enough';
            break; 
        }
        
        var battleReport = attacker.fight(defender);
        var awards = [];
        if( battleReport.success ) {
            player.costResource('food', costFood)

            myBattleProgress[battleFieldId] = battleId;
            player.markDirty(util.format('mybattle.progress.%d', battleFieldId));

            if( battleId > myBattle.max ) {
                myBattle.max = battleId; 
                player.markDirty('mybattle.max');
                player.checkEvent('MyDuplicate', battleId);
            }

            if( battleConf.Award1 ) {
                awards.push(battleConf.Award1);
            }

            if( common.randRange(1, 100) <= battleConf.Rate ) {
                awards.push(['material', battleConf.MaterialId, 
                    +common.randRange(battleConf.Min, battleConf.Max)]); 
            }

            var roleCardId = battleConf.RoleCardId;
            if( user.role[roleCardId] && common.randRange(1, 100) <= battleConf.RoleCardRate ) {
                awards.push(['card', battleConf.RoleCardId, 
                    +common.randRange(battleConf.RoleCardMin, battleConf.RoleCardMax)]); 
            }

            awards = player.addAwards(awards);
        }else {
            costFood = 0; 
        }

        resp.data.battle = battleReport;
        resp.data.food = -costFood;
        resp.data.awards = awards;
    }while(false);   
    
    onHandled();
}

exports.reset_mybattle = function(player, req, resp, onHandled){
    do {
        if( isNaN(req.args.id) ){
            resp.code = 1; resp.desc = 'no valid args'; break;
        }

        var isCash = req.args.cash ? true : false;
        var battleFieldId = parseInt(req.args.id);

        var user = player.user;
        var myBattle = user.mybattle;
        var costCash = 0;
        
        if( !myBattle.progress[battleFieldId] ) {
            resp.code = 1; resp.desc = 'id error'; break;
        }

        if( !isCash && myBattle.free >= +gConfGlobal.MyBattleFreeResetLimit ) {
            resp.code = 1; resp.desc = 'no more free'; break;
        }

        if( !isCash ) {
            myBattle.free += 1;
            player.markDirty('mybattle.free');
        }else {
            var confBuy = gConfBuy[myBattle.cash + 1]; 
            if( !confBuy ) {
                resp.code = 1; resp.desc = 'no more to buy'; break;
            }
            
            costCash = +confBuy.CashMyBattleReset;
            if( !costCash ) {
                resp.code = 1; resp.desc = 'no more to buy'; break;
            }

            if( !player.costResource('cash', costCash, myBattle.cash) ){
                resp.code = 1; resp.desc = 'not enough cash'; break;
            }

            myBattle.cash += 1;
            player.markDirty('mybattle.cash');
        }
        
        myBattle.progress[battleFieldId] = 0;
        player.markDirty(util.format('mybattle.progress.%d', battleFieldId));

        resp.data.cash = -costCash; 
    
    }while(false);       
    
    onHandled();
}
